package com.atguigu.gulimail.product.exception;

import com.atguigu.common.utils.BizException;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.atguigu.common.utils.BizException.VAILD_EXCEPTION;

//表示对com.atguigu.gulimail.product.controller中的所有异常进行统一处理
@Slf4j
@ResponseBody
@RestController
@ControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
public class GulimailException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValue(MethodArgumentNotValidException e){ //获取数据校验类型的报错
        log.error("数据校验出现问题{}\n异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult=e.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach((i)->{
            errorMap.put(i.getField(),i.getDefaultMessage());
        });
        return R.error(VAILD_EXCEPTION.getCode(),VAILD_EXCEPTION.getMessage()).put("data",errorMap);
    }



    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.info(throwable.getMessage());
        return R.error(BizException.UNKNOW_EXCEPTION.getCode(), BizException.UNKNOW_EXCEPTION.getMessage());
    }
}

